<?php

namespace App\Services;

use Illuminate\Support\Facades\Redis;

/**
 * 处理和 Laravel Echo Server 相关的数据
 *
 * Class EchoServer
 * @package App\Services
 */
class EchoServer
{
    protected $redis;
    
    public function __construct($connection)
    {
        $this->redis = Redis::connection($connection);
    }
    
    /**
     * 从 Presence Channel 中获取用户数据
     *
     * @param string $channel
     * @return array
     */
    public function getMembers($channel)
    {
        $key = "presence-{$channel}:members";
        
        if (! $data = $this->redis->get($key)) {
            return [];
        }
        
        return json_decode($data, true);
    }
    
    /**
     * 修改 Presence Channel 中的用户数据
     *
     * @param string $channel
     * @param array $members
     */
    public function setMembers($channel, $members)
    {
        $key = "presence-{$channel}:members";
        
        $data = json_encode($members);
        
        $this->redis->set($key, $data);
    }
}
